package cn.chiship.framework.business.middleware.redis;

import cn.chiship.framework.business.biz.cashier.service.impl.AsyncCashierService;
import cn.chiship.framework.common.constants.CommonCacheConstants;
import cn.chiship.sdk.core.util.PrintUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * @author lijian
 */
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

	@Autowired
	private AsyncCashierService asyncCashierService;

	public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
		super(listenerContainer);
	}

	@Override
	public void onMessage(Message message, byte[] pattern) {
		// 注意：只能获取失效的key值，获取不到key对应的value值的。
		String expireKey = message.toString();
		PrintUtil.console("触发RedisKey失效监听器", expireKey);
		try {
			if (!StringUtils.isEmpty(expireKey)) {
				String[] keys = expireKey.split(":");
				if (expireKey.contains(
						CommonCacheConstants.buildKey(CommonCacheConstants.REDIS_TIMEOUT_CLOSED_ORDER_PREFIX))) {
					String orderNo = keys[keys.length - 1];
					asyncCashierService.orderTimeoutClosed(orderNo);
				}
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}

}
